package com.yanfan.zutai.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yanfan.common.annotation.Anonymous;
import com.yanfan.common.core.controller.BaseController;
import com.yanfan.common.core.domain.AjaxResult;
import com.yanfan.common.core.domain.entity.SysUser;
import com.yanfan.common.core.mq.MQSendMessageBo;
import com.yanfan.common.core.mq.message.FunctionCallBackBo;
import com.yanfan.common.core.page.TableDataInfo;
import com.yanfan.common.core.redis.RedisCache;
import com.yanfan.common.utils.DateUtils;
import com.yanfan.common.utils.StringUtils;
import com.yanfan.common.utils.uuid.IdUtils;
import com.yanfan.framework.web.service.TokenService;
import com.yanfan.iot.domain.Device;
import com.yanfan.iot.model.DeviceAllShortOutput;
import com.yanfan.iot.model.ThingsModels.ValueItem;
import com.yanfan.iot.service.IDeviceService;
import com.yanfan.iot.service.IThingsModelService;
import com.yanfan.iot.tdengine.config.TDengineDatabaseConfig;
import com.yanfan.iot.tdengine.dao.ZuTaiTDengineMapper;
import com.yanfan.mqtt.manager.MqttRemoteManager;
import com.yanfan.mqtt.model.PushMessageBo;
import com.yanfan.mqttclient.PubMqttClient;
import com.yanfan.protocol.base.protocol.IProtocol;
import com.yanfan.protocol.service.IProtocolManagerService;
import com.yanfan.zutai.controller.xunraostrage.ConsumerXunrao;
import com.yanfan.zutai.controller.xunraostrage.XunraoFactory;
import com.yanfan.zutai.domain.*;
import com.yanfan.zutai.domain.vo.ZutaiDataVo;
import com.yanfan.zutai.mapper.BCommonMapper;
import com.yanfan.zutai.service.BCommonService;
import com.yanfan.zutai.service.IBDeviceHistoryDataService;
import com.yanfan.zutai.service.IBDeviceZtUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.*;


@RestController
@RequestMapping("/zutai")
@Api(value = "组态管理", tags = "组态管理")
public class ZutaiController extends BaseController {
    public static final String ZT_DATA = "ZT_DATA:";
    /**
     * 获取设备管理详细信息，-2已过期，-1没有设置有效期，0以上的值表示是这个key的剩余有效时间
     */
    @Autowired
    private BCommonMapper commonMapper;
    @Autowired
    private BCommonService bCommonService;

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Resource
    private PubMqttClient mqttClient;
    @Autowired
    private IDeviceService deviceService;

    @Autowired
    private IThingsModelService thingsModelService;

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private XunraoFactory xunraoFactory;
    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private IBDeviceHistoryDataService bDeviceHistoryDataService;

    @Autowired
    private IBDeviceZtUserService bdeviceZtUserService;

    @Value("${spring.datasource.druid.tdengine-server.enabled}")
    private Boolean enabled;
    @Resource
    private MqttRemoteManager remoteManager;

    @Resource
    private IProtocolManagerService protocolManagerService;

    @Autowired
    private TDengineDatabaseConfig tDengineDatabaseConfig;

    @Autowired(required = false)
    private ZuTaiTDengineMapper zuTaiTDengineMapper;

    /**
     * 2. 获取组态详情
     *
     * @param deviceMac
     * @param guid
     * @return
     */

    @ApiOperation(value = "设备组态详情")
    @GetMapping(value = "/bDeviceZt/getZtData")
    public AjaxResult getZtData(String deviceMac, String guid) {
        if ("undefined".equals(deviceMac)) {
            deviceMac = null;
        }
        if ("null".equals(deviceMac)) {
            deviceMac = null;
        }
        BDeviceZt bDeviceZt = commonMapper.getZtData(deviceMac, guid);
        return AjaxResult.success(bDeviceZt);
    }

    /**
     * 3 获取组态绑定的设备数，一个组态可以绑定多个设备，用于多个设备的参数绑定
     *
     * @param ztGuid
     * @return
     */
    @GetMapping(value = "/bDeviceZtBind/getDeviceBind")
    public TableDataInfo getDeviceBind(
            String ztGuid,
            String deviceName,
            @RequestParam(required = false) Integer pageNum,
            @RequestParam(required = false) Integer pageSize
    ) {
        //        PageHelper.startPage(pageNum,pageSize);
        //        startPage();
        BDeviceZtBind bDeviceZtBind = new BDeviceZtBind();
        bDeviceZtBind.setZtGuid(ztGuid);
        bDeviceZtBind.setDeviceName(deviceName);
        List<BDeviceZtBind> list = commonMapper.selectBDeviceZtBindList(bDeviceZtBind);
        //        PageInfo<BDeviceZtBind> pageInfo = new PageInfo<>(list);
        TableDataInfo dataTable = getDataTable(list);
        //        dataTable.setTotal(pageInfo.getTotal());
        return dataTable;
    }


    //  /**
    //   * 查询云组态组件关联列表
    //   */
    //  @GetMapping("/bDeviceZtBind/getDeviceBind")
    //  public TableDataInfo getDeviceBind(BDeviceZtBind bDeviceZtBind)
    //  {
    //    List<BDeviceZtBindVo> bindVoList=new ArrayList<>();
    //    if(Detect.isEmpty(bDeviceZtBind.getZtGuid())){
    //      return getDataTable(bindVoList);
    //    }
    //    StringBuilder stringBuilder=new StringBuilder();
    //    stringBuilder.append("select z.id,d.device_name,d.installation_address,d.remark,d.device_mac,d.latitude,d.longitude " +
    //      " from b_device_manager d ,b_device_zt_bind z where d.device_mac=z.device_mac");
    //    stringBuilder.append(" and z.zt_guid=?");
    //    if(Detect.notEmpty(bDeviceZtBind.getDeviceName())){
    //      stringBuilder.append(" and d.device_name like ?");
    //    }
    //    stringBuilder.append(" order by id desc");
    //    BeanPropertyRowMapper<BDeviceZtBindVo> bDeviceMaintainRowMapper = new BeanPropertyRowMapper<>(BDeviceZtBindVo.class);
    //    if(Detect.notEmpty(bDeviceZtBind.getDeviceName())){
    //      bindVoList=jdbcTemplate.query(stringBuilder.toString(), bDeviceMaintainRowMapper,bDeviceZtBind.getZtGuid(),
    //        "%"+bDeviceZtBind.getDeviceName()+"%");
    //    }else{
    //      bindVoList=jdbcTemplate.query(stringBuilder.toString(), bDeviceMaintainRowMapper,bDeviceZtBind.getZtGuid());
    //    }
    //    return getDataTable(bindVoList);
    //  }

    /**
     * 4 获取变量管理数据，用于绑定变量
     *
     * @param bDeviceRealData
     * @return
     */
    @ApiOperation(value = "获取变量管理数据")
    @GetMapping("/bDeviceRealData/getBindDatalist")
    public TableDataInfo getBindDatalist(
            BDeviceRealData bDeviceRealData,
            @RequestParam(required = false) Integer pageNum,
            @RequestParam(required = false) Integer pageSize
    ) {
        List<BDeviceRealData> list = new ArrayList<>();
        if (StrUtil.isEmpty(bDeviceRealData.getZtGuid())) {
            return getDataTable(list);
        }
        PageHelper.startPage(pageNum, pageSize);
        list = commonMapper.selectDeviceAndModels(bDeviceRealData.getZtGuid(), bDeviceRealData.getParamDoubleQuery());
        PageInfo<BDeviceRealData> pageInfo = new PageInfo<>(list);
        TableDataInfo dataTable = getDataTable(list);
        dataTable.setTotal(pageInfo.getTotal());
        return dataTable;
    }

    /**
     * 8 保存组态
     *
     * @param bDeviceZt
     * @return
     */

    @ApiOperation(value = "保存组态")
    @PostMapping(value = "/bDeviceZt/saveZt")
    public AjaxResult saveZt(@RequestBody BDeviceZt bDeviceZt) {
        if (StrUtil.isEmpty(bDeviceZt.getGuid())/* || StrUtil.isEmpty(bDeviceZt.getDeviceMac())*/) {
            return AjaxResult.error("参数不符合规定");
        }
        BDeviceZt bDeviceZtQuery = new BDeviceZt();
        bDeviceZtQuery.setGuid(bDeviceZt.getGuid());
        bDeviceZtQuery.setDeviceMac(bDeviceZt.getDeviceMac());
        List<BDeviceZt> bDeviceZts = commonMapper.selectBDeviceZtList(bDeviceZtQuery);
        if (bDeviceZts.size() > 0) {
            BDeviceZt deviceZt = bDeviceZts.get(0);
            deviceZt.setDeviceZtData(bDeviceZt.getDeviceZtData());
            commonMapper.updateBDeviceZt(deviceZt);
        } else {
            bDeviceZt.setCreateTime(new Date());
            commonMapper.insertBDeviceZt(bDeviceZt);
            BDeviceZtBind bDeviceZtBind = new BDeviceZtBind();
            bDeviceZtBind.setDeviceMac(bDeviceZt.getDeviceMac());
            bDeviceZtBind.setZtGuid(bDeviceZt.getGuid());
            commonMapper.insertBDeviceZtBind(bDeviceZtBind);
        }
        return AjaxResult.success();
    }

    @GetMapping(value = "/bDeviceRealData/getInitData")
    public AjaxResult getInitData(String ztGuid) {
        BDeviceZtBind bDeviceZtBind = new BDeviceZtBind();
        bDeviceZtBind.setZtGuid(ztGuid);
        List<BDeviceZtBind> list = commonMapper.selectBDeviceZtBindList(bDeviceZtBind);
        List<Map<String, String>> result = new ArrayList();
        for (BDeviceZtBind deviceZtBind : list) {
            Map<String, String> cacheMap = redisCache.getCacheMap(ZT_DATA + deviceZtBind.getDeviceMac());
            cacheMap.put("imei", deviceZtBind.getDeviceMac());
            result.add(cacheMap);
        }

        return AjaxResult.success(result);
    }

    @GetMapping(value = "/bDeviceZtBind/list")
    public TableDataInfo bDeviceZtBind(String ztGuid) {
        //        startPage();
        BDeviceZtBind bDeviceZtBind = new BDeviceZtBind();
        bDeviceZtBind.setZtGuid(ztGuid);
        List<BDeviceZtBind> list = commonMapper.selectBDeviceZtBindList(bDeviceZtBind);
        return getDataTable(list);
    }

    @GetMapping("/bDeviceZt/list")
    public TableDataInfo list(BDeviceZt bDeviceZt) {
        SysUser user = getLoginUser().getUser();
        if (!user.isAdmin()) {
            bDeviceZt.setUserId(user.getUserId());
        }
        startPage();
        List<BDeviceZt> list = commonMapper.selectBDeviceZtList(bDeviceZt);
        return getDataTable(list);
    }

    @GetMapping("/bDeviceZt/listfp")
    public TableDataInfo listfp(BDeviceZt bDeviceZt) {
        startPage();
        List<BDeviceZt> list = commonMapper.selectBDeviceZtList(bDeviceZt);
        return getDataTable(list);
    }

    @GetMapping("/bDeviceZt/listztuser")
    public TableDataInfo listztuser(BDeviceZt bDeviceZt) {
        SysUser user = getLoginUser().getUser();
        if (!user.isAdmin()) {
            bDeviceZt.setUserId(user.getUserId());
        }
        startPage();
        List<BDeviceZt> list = commonMapper.selectBDeviceZtListUser(user.getDeptId(), bDeviceZt.getPageName());
        return getDataTable(list);
    }

    /*@GetMapping("/bDeviceManager/getArea")
    public AjaxResult getArea() {
        JSONArray area1 = JSONUtil.parseArray(StaticString.AREA1);
        return AjaxResult.success(area1);

    }*/

    @GetMapping("/upload/list")
    public TableDataInfo list(SysUpload sysUpload) {
        startPage();
        List<SysUpload> list = commonMapper.selectSysUploadList(sysUpload);
        return getDataTable(list);
    }

    @PutMapping("/bDeviceZt")
    public AjaxResult savebDeviceZt(@RequestBody BDeviceZt bDeviceZt) {
        if (bDeviceZt.getIsMainPage() != null && bDeviceZt.getIsMainPage() == 1 && StrUtil.isNotBlank(bDeviceZt.getDeviceMac())) {
            String ztSql = "update b_device_zt set is_main_page =0 where device_mac=? and guid!=?";
            jdbcTemplate.update(ztSql, bDeviceZt.getDeviceMac(), bDeviceZt.getGuid());
        }
        commonMapper.updateBDeviceZt(bDeviceZt);
        return toAjax(true);
    }

    @ApiOperation(value = "删除组态")
    @DeleteMapping("/bDeviceZt/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(commonMapper.deleteBDeviceZtByIds(ids));
    }

    /**
     * 查询设备实时数据列表
     */
    @ApiOperation(value = "查询设备实时数据列表")
    @GetMapping("/bDeviceRealData/list")
    public TableDataInfo list(BDeviceRealData bDeviceRealData) {
        startPage();
        List<ValueItem> valueItemList = new ArrayList<>();
        if (StrUtil.isNotBlank(bDeviceRealData.getZtGuid())) {
            String ztSql = "select * from b_device_zt_bind where zt_guid=?";
            BeanPropertyRowMapper<BDeviceZtBind> bindBeanPropertyRowMapper = new BeanPropertyRowMapper<>(BDeviceZtBind.class);
            List<BDeviceZtBind> ztBinds = jdbcTemplate.query(ztSql, bindBeanPropertyRowMapper, bDeviceRealData.getZtGuid());
            for (BDeviceZtBind ztBind : ztBinds) {
                //获取设备的实时数据
                List<ValueItem> valueItems = deviceService.selectDeviceBySerialNumberDw(ztBind.getDeviceMac());
                valueItemList.addAll(valueItems);
            }
        }
        return getDataTable(valueItemList);
    }


    @ApiOperation(value = "设备组态数据上报")
    @PostMapping(value = "/bDeviceRealData/orderSend")
    public AjaxResult orderSend(@RequestBody BDeviceRealData bDeviceRealData) {
        if (StrUtil.isEmpty(bDeviceRealData.getParamValue())) {
            return AjaxResult.error("变量值为空，无法设置");
        }
        //String topic = "/IOT/WULIANYUN/ORDERSEND/" + bDeviceRealData.getDeviceImei();
        Device device = deviceService.selectDeviceBySerialNumber(bDeviceRealData.getDeviceImei());
        // List<Map> requestParam = new ArrayList<>();
        //if (device.getProtocolCode().equals("JSONOBJECT")) {
        //    // 创建一个JSONObject
        //    JSONObject jsonObject = new JSONObject();
        //    // 将参数字段和值放入JSONObject
        //    jsonObject.put(bDeviceRealData.getParamField(), bDeviceRealData.getParamValue());
        //    // 将JSONObject转换为字符串
        //    message1 = jsonObject.toJSONString();
        //} else {
        //    Map map1 = new HashMap();
        //    map1.put("id", bDeviceRealData.getParamField());
        //    map1.put("value", bDeviceRealData.getParamValue());
        //    requestParam.add(map1);
        //    message1 = JSON.toJSONString(requestParam);
        //}
        /**
         * 更改此处的原因是
         * （1）之前如果通讯协议不是JSONOBJECT 或 JSONARRAY，则组态下发数据会失败
         * （2）数据直接在这里组装每种都要单独在这里组装，不优雅
         * （3）匹配当前设备协议，下发做编码处理，返回实际要下发的数据
         */
        String message1 = null;
        try {
            IProtocol protocol = protocolManagerService.getProtocolByProtocolCode(device.getProtocolCode());
            //组装协议中encode编码方法入口对象
            MQSendMessageBo mqSendMessageBo = new MQSendMessageBo();
            mqSendMessageBo.setSerialNumber(device.getSerialNumber());
            mqSendMessageBo.setIdentifier(bDeviceRealData.getParamField());
            mqSendMessageBo.setValue(bDeviceRealData.getParamValue());

            JSONObject jsonObject = new JSONObject();
            jsonObject.put(bDeviceRealData.getParamField(), bDeviceRealData.getParamValue());
            mqSendMessageBo.setParams(jsonObject);

            FunctionCallBackBo encode = protocol.encode(mqSendMessageBo);
            byte[] encodeMessage = encode.getMessage();

            message1 = new String(encodeMessage, StandardCharsets.UTF_8);
            if (StringUtils.isEmpty(message1)) {
                return AjaxResult.error("匹配协议编码失败，请检查协议编码是否正确");
            }
        } catch (Exception e) {
            return AjaxResult.error("匹配协议编码失败，" + e.getMessage());
        }

        //判断是否为自定义主题
        String wumeiTopic = "/" + device.getProductId() + "/" + bDeviceRealData.getDeviceImei() + "/function/get";
        // mqttClient.publish(1, false, wumeiTopic, message1);
        //if(bDeviceRealData.getDataType()!=null&&bDeviceRealData.getDataType()==4){
        //    bDeviceRealData.setParamValue(Convert.toFloat(bDeviceRealData.getParamValue()).toString());
        //}else{
        //    bDeviceRealData.setParamValue(Convert.toInt(bDeviceRealData.getParamValue()).toString());
        //}
        //BDeviceDataTestVo mapping = BeanUtil.copyProperties(bDeviceRealData, BDeviceDataTestVo.class);
        //String message = JSON.toJSONString(mapping);
        //try {
        //    mqttClient.publish(1, false, topic, message);
        //    //            // 发送至前端
        //    PushMessageBo messageBo = new PushMessageBo();
        //    messageBo.setTopic(topic);
        //    messageBo.setMessage(message);
        //    remoteManager.pushCommon(messageBo);
        //} catch (Exception e) {
        //    System.out.println("mqtt消息发送失败，" + e);
        //    return AjaxResult.error("mqtt消息发送失败");
        //}
        // 讯绕topic,策略加工厂模式
        ConsumerXunrao consumer = xunraoFactory.getConsumer(device);
        if (consumer != null) {
            consumer.consumer(mqttClient, bDeviceRealData);
        }
        // redisService.setStr("orderSend-"+bDeviceRealData.getDeviceImei(),"success",null);
        // 方便测试，发送设置指令立即返回成功指令
        //Map<String, Object> map = new HashMap<>();
        try {
            //String replyTopic = "/IOT/WULIANYUN/ORDERSEND/" + bDeviceRealData.getDeviceImei();
            //map.put(bDeviceRealData.getParamField(), bDeviceRealData.getParamValue());
            //String replyMsg = JSON.toJSONString(map);
            if (device.getMqttstats() == 1) {
                mqttClient.publish(1, false, device.getGetDev(), message1);
                //发送至前端
                PushMessageBo messageBo = new PushMessageBo();
                messageBo.setTopic(wumeiTopic);
                messageBo.setMessage(message1);
                remoteManager.pushCommon(messageBo);
            } else {
                mqttClient.publish(1, false, wumeiTopic, message1);
            }
            // 插入变量历史数据,改用taos时序数据库
            BDeviceHistoryData historyData = new BDeviceHistoryData();
            historyData.setParamField(bDeviceRealData.getParamField());
            historyData.setParamName(bDeviceRealData.getParamName());
            historyData.setParamValue(bDeviceRealData.getParamValue());
            historyData.setParamUnit(bDeviceRealData.getParamUnit());
            historyData.setReportTime(bDeviceRealData.getReportTime());
            historyData.setDeviceImei(bDeviceRealData.getDeviceImei());
            historyData.setDeptIdStrs(null);
            historyData.setDeviceName(bDeviceRealData.getDeviceName());
            if (enabled) {
                try {
                    insertTaosHistory(historyData);
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("插入时序数据库出错");
                }
            } else {
                bDeviceHistoryDataService.insertBDeviceHistoryData(historyData);
            }
        } catch (Exception e) {
            return AjaxResult.error("mqtt消息发送失败，{}" + e.getMessage());
        }
        return AjaxResult.success();
    }

    /**
     * 新增云组态
     */
    @ApiOperation(value = "新增云组态", notes = "新增云组态")
    @PostMapping("/bDeviceZt")
    public AjaxResult add(@RequestBody BDeviceZt bDeviceZt) {
        if (bDeviceZt.getIsMainPage() != null && bDeviceZt.getIsMainPage() == 1 && StrUtil.isNotBlank(bDeviceZt.getDeviceMac())) {
            String ztSql = "update b_device_zt set is_main_page =0 where device_mac=?";
            jdbcTemplate.update(ztSql, bDeviceZt.getDeviceMac());
        }
        bDeviceZt.setGuid(UUID.randomUUID().toString());
        bDeviceZt.setCreateBy("admin");
        if (StrUtil.isNotBlank(bDeviceZt.getDeviceMac())) {
            BDeviceZtBind bDeviceZtBind = new BDeviceZtBind();
            bDeviceZtBind.setDeviceMac(bDeviceZt.getDeviceMac());
            bDeviceZtBind.setZtGuid(bDeviceZt.getGuid());
            commonMapper.insertBDeviceZtBind(bDeviceZtBind);
        }
        bDeviceZt.setCreateTime(new Date());
        int insertCount = commonMapper.insertBDeviceZt(bDeviceZt);
        if (insertCount > 0) {
            SysUser curr = getLoginUser().getUser();
            // 添加设备用户
            BDeviceZtUser ztUser = new BDeviceZtUser();
            ztUser.setUserId(curr.getUserId());
            ztUser.setUserName(curr.getUserName());
            ztUser.setPhonenumber(curr.getPhonenumber());
            ztUser.setZtId(String.valueOf(bDeviceZt.getId()));
            ztUser.setZtName(bDeviceZt.getPageName());
            ztUser.setTenantId(curr.getDeptId());
            ztUser.setTenantName(curr.getUserName());
            ztUser.setIsOwner(1L);
            ztUser.setCreateTime(DateUtils.getNowDate());
            bdeviceZtUserService.insertBDeviceZtUser(ztUser);
        }
        return toAjax(insertCount);
    }

    /**
     * 获取云组态详细信息
     */
    @ApiOperation(value = "图表调用", notes = "图表调用")
    @GetMapping(value = "/bDeviceZt/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(commonMapper.selectBDeviceZtById(id));
    }

    /**
     * 获取设备列表，用于绑定
     */
    @ApiOperation(value = "获取设备列表，用于绑定", notes = "获取设备列表，用于绑定")
    @GetMapping(value = "/bDeviceManager/list")
    public TableDataInfo list(
            BDeviceManager bDeviceManager,
            @RequestParam(required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize
    ) {
        //        startPage();
        PageHelper.startPage(pageNum, pageSize);
        if (StrUtil.isNotBlank(bDeviceManager.getQueryDeptId())) {
            bDeviceManager.setDeptIdStrs(bDeviceManager.getQueryDeptId());
        }
        List<BDeviceManager> list = new ArrayList<>();
        Device device1 = new Device();
        SysUser user = getLoginUser().getUser();
        if (!user.isAdmin()) {
            // 租户查看产品下所有设备
            device1.setTenantId(user.getUserId());
        }
        if (StringUtils.isNotEmpty(bDeviceManager.getDeviceName())) {
            device1.setDeviceName(bDeviceManager.getDeviceName());
        }
        List<DeviceAllShortOutput> deviceAllShortOutputs = deviceService.selectAllDeviceShortList(device1);
        PageInfo<DeviceAllShortOutput> pageInfo = new PageInfo<>(deviceAllShortOutputs);
        for (DeviceAllShortOutput device : deviceAllShortOutputs) {
            BDeviceManager deviceManager = new BDeviceManager();
            deviceManager.setDeviceMac(device.getSerialNumber());
            deviceManager.setDeviceName(device.getDeviceName());
            deviceManager.setGuid(device.getDeviceId() + "");
            deviceManager.setLatitude(device.getLatitude());
            deviceManager.setLongitude(device.getLongitude());
            list.add(deviceManager);
        }
        TableDataInfo dataTable = getDataTable(list);
        dataTable.setTotal(pageInfo.getTotal());
        return dataTable;
    }

    /**
     * 组件关联设备
     *
     * @param bDeviceZtBind
     * @return
     */
    @ApiOperation(value = "组件关联设备", notes = "组件关联设备")
    @PostMapping("/bDeviceZtBind")
    public AjaxResult add(@RequestBody BDeviceZtBind bDeviceZtBind) {
        List<BDeviceZtBind> bindList = commonMapper.selectBDeviceZtBindList(bDeviceZtBind);
        if (bindList.size() > 0) {
            return AjaxResult.error("设备已绑定");
        } else {
            commonMapper.insertBDeviceZtBind(bDeviceZtBind);
            return toAjax(true);
        }
    }

    /**
     * 删除云组态组件关联
     */
    @ApiOperation(value = "删除云组态组件关联", notes = "删除云组态组件关联")
    @DeleteMapping("/bDeviceZtBind/{ids}")
    public AjaxResult removeBDeviceZtBind(@PathVariable Long[] ids) {
        return toAjax(commonMapper.deleteBDeviceZtBindByIds(ids));
    }

    /**
     * 删除日志
     * 定时任务
     */
    public void deleteLog() {
        String yesterday = DateUtil.yesterday().toString("yyyy-MM-dd HH:mm:ss");
        commonMapper.deleteFunctionLog(yesterday);
        commonMapper.deleteDeviceLog(yesterday);
    }

    public void insertTaosHistory(BDeviceHistoryData bDeviceHistoryData) throws Exception {
        Snowflake snowflake = IdUtil.getSnowflake(6, 2);
        long id = snowflake.nextId();
        bDeviceHistoryData.setId(id);
        String sql = "INSERT INTO `{}` USING `" + tDengineDatabaseConfig.getDbName() + "`.`b_device_history_data` TAGS({}) VALUES " + "({}, '{}', '{}','{}','{}','{}','{}','{}');";
        String formatSql = StrUtil.format(sql,
                "d" + bDeviceHistoryData.getDeviceImei(),
                bDeviceHistoryData.getId(),
                IdUtils.nextTaosNsId(),
                bDeviceHistoryData.getDeptIdStrs(),
                bDeviceHistoryData.getDeviceImei(),
                bDeviceHistoryData.getDeviceName(),
                bDeviceHistoryData.getParamName(),
                bDeviceHistoryData.getParamField(),
                bDeviceHistoryData.getParamValue(),
                bDeviceHistoryData.getParamUnit()
        );
        zuTaiTDengineMapper.updateBySql(formatSql);
    }


    /**
     * 获取当前用户的登录ID 方便直接跳转到页面
     */
    @GetMapping(value = "/getLoginId")
    public AjaxResult getCurrUserLoginId() {
        return AjaxResult.success("操作成功", bCommonService.getCurrUserLoginId());
    }


    /**
     * 组态复制
     */
    @ApiOperation(value = "组态复制", notes = "组态复制")
    @Anonymous
    @PostMapping("/bDeviceZtCopy")
    public AjaxResult copy(@RequestBody BDeviceZt bDeviceZt) {
        bDeviceZt.setGuid(UUID.randomUUID().toString());
        bDeviceZt.setCreateBy("admin");
        if (StrUtil.isNotBlank(bDeviceZt.getDeviceMac())) {
            BDeviceZtBind bDeviceZtBind = new BDeviceZtBind();
            bDeviceZtBind.setDeviceMac(bDeviceZt.getDeviceMac());
            bDeviceZtBind.setZtGuid(bDeviceZt.getGuid());
            commonMapper.insertBDeviceZtBind(bDeviceZtBind);
        }
        bDeviceZt.setCreateTime(new Date());
        int insertCount = commonMapper.insertBDeviceZt(bDeviceZt);
        if (insertCount > 0) {
            SysUser curr = getLoginUser().getUser();
            // 添加设备用户
            BDeviceZtUser ztUser = new BDeviceZtUser();
            ztUser.setUserId(curr.getUserId());
            ztUser.setUserName(curr.getUserName());
            ztUser.setPhonenumber(curr.getPhonenumber());
            ztUser.setZtId(String.valueOf(bDeviceZt.getId()));
            ztUser.setZtName(bDeviceZt.getPageName());
            ztUser.setTenantId(curr.getDeptId());
            ztUser.setTenantName(curr.getUserName());
            ztUser.setIsOwner(1L);
            ztUser.setCreateTime(DateUtils.getNowDate());
            bdeviceZtUserService.insertBDeviceZtUser(ztUser);
        }
        return toAjax(insertCount);
    }

    @ApiOperation("分配图表")
    @PostMapping("/dict/list")
    public AjaxResult assignment(@RequestBody DictDTO dictDTO) {
        if (null == dictDTO.getDeptId()) {
            return error("请选择分配机构");
        }
        if (StringUtils.isEmpty(dictDTO.getZutaiId())) {
            return error("请选择图表");
        }
        return bdeviceZtUserService.insertfpUser(dictDTO.getDeptId(), dictDTO.getZutaiId());
    }

    @GetMapping("/zutaiList")
    public AjaxResult zutaiList() {
        return AjaxResult.success(bdeviceZtUserService.zutaiList());
    }

    @PostMapping(value = "/bDeviceZtList")
    @Anonymous
    public AjaxResult bDeviceZtList(@RequestBody ZutaiDataVo zutaiDataVo) {
        return bdeviceZtUserService.bDeviceZtList(zutaiDataVo);
    }
}
